import * as THREE from 'three';
import * as CANNON from 'cannon-es';

export default class PhysicsWorld {
    constructor(scene) {
        this.scene = scene;
        this.groundSize = 100;
        this.groundThickness = 0.2;
        
        // 初始化物理世界
        this.initPhysics();
        this.createGround();
    }
    
    initPhysics() {
        this.world = new CANNON.World({
            gravity: new CANNON.Vec3(0, -9.82, 0),
        });
        this.world.broadphase = new CANNON.SAPBroadphase(this.world);
        this.world.solver.iterations = 15;
        this.world.allowSleep = true;
        
        console.log('物理世界初始化完成');
    }
    
    createGround() {
        // 创建地面材质
        this.groundMaterial = new CANNON.Material('ground');
        
        // 创建地面形状
        const groundShape = new CANNON.Box(new CANNON.Vec3(
            this.groundSize / 2,
            this.groundThickness / 2,
            this.groundSize / 2
        ));
        
        // 创建地面刚体
        this.groundBody = new CANNON.Body({
            mass: 0, // 静态
            material: this.groundMaterial,
            shape: groundShape,
            position: new CANNON.Vec3(0, -this.groundThickness / 2, 0)
        });
        this.world.addBody(this.groundBody);
        
        // 创建地面网格
        const groundGeometry = new THREE.BoxGeometry(
            this.groundSize,
            this.groundThickness,
            this.groundSize
        );
        const groundMeshMaterial = new THREE.MeshStandardMaterial({
            color: 0x555555,
            metalness: 0.1,
            roughness: 0.9
        });
        this.groundMesh = new THREE.Mesh(groundGeometry, groundMeshMaterial);
        this.groundMesh.receiveShadow = true;
        this.groundMesh.position.copy(this.groundBody.position);
        this.scene.add(this.groundMesh);
        
        // 添加网格辅助线
        const gridHelper = new THREE.GridHelper(this.groundSize, 20, 0xcccccc, 0xcccccc);
        gridHelper.position.y = 0.01;
        this.scene.add(gridHelper);
        
        console.log('地面创建完成');
    }
    
    update(dt) {
        const fixedTimeStep = 1 / 60;
        const maxSubSteps = 5;
        this.world.step(fixedTimeStep, dt, maxSubSteps);
    }
    
    getWorld() {
        return this.world;
    }
    
    getGroundMaterial() {
        return this.groundMaterial;
    }
}